package book.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录过滤器
 * 作用：当uri请求是：*.do 验证用户是否登录
 */
@WebFilter("*.do")
public class BLoginFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        //1、判断用户是否已经登录
        if(null == req.getSession().getAttribute("username")){
            //未登录，跳转登录页面
            req.getSession().setAttribute("msg","请先登录！");
//            res.sendRedirect("/login.jsp");
            res.sendRedirect(req.getContextPath() + "/login.jsp");  // 推荐：加上应用上下文路径
            return;
        }
        //已经登录，对请求放行
        chain.doFilter(req, res);
    }
}
